<template>
  <div>
    <el-card>
      <el-button @click="goBack" style="margin-bottom:15px">返回</el-button>
      <el-button type="success" @click="showAddQuestion">添加常见问题</el-button>
      <br />

      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="问题标题:">
          <el-input
            v-model="questionQuery.queTitle"
            placeholder="请输入问题标题"
            clearable
            @change="getRobotQuestion"
          ></el-input>
        </el-form-item>
        <el-form-item label="问题关键字:">
          <el-input
            v-model="questionQuery.queKeyword"
            placeholder="请输入问题关键字"
            clearable
            @change="getRobotQuestion"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-table
        :data="questionList"
        border
        style="width: 99%"
        @expand-change="exChange"
        :row-key="getRowKeys"
        :expand-row-keys="expands"
      >
        <el-table-column label="详情" width="80" type="expand">
          <template slot-scope="scoped">
            <div>
              <el-table
                :data="detialList"
                border
                style="width: 100%;margin-left:30px"
                :show-header="showHeader"
              >
                <el-table-column prop="queType" label width="100">
                  <template slot-scope="scope">
                    <div>
                      <el-tag v-if="scope.row.queType==2" type="success">详情问题</el-tag>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="queTitle" width="300"></el-table-column>
                <el-table-column prop="queKeyword" width="300">
                  <template slot-scope="scoped">
                    <div>
                      <el-tag
                        type="info"
                        v-for="(item,index) in scoped.row.queKeyword"
                        :key="index"
                      >{{item}}</el-tag>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="queDescribe" width="300"></el-table-column>
                <el-table-column prop="companyName"></el-table-column>
                <el-table-column prop="deviceTypeName"></el-table-column>
                <el-table-column fixed="right" width="280">
                  <template slot-scope="scope">
                    <el-button
                      v-if="scope.row.isHaveAns==1"
                      type="primary"
                      size="small"
                      @click="showAnswer(scope.row.id)"
                    >查看回复</el-button>
                    <el-button
                      v-else-if="scope.row.isHaveAns==2"
                      type="success"
                      size="small"
                      @click="addAnswer(scope.row.id)"
                    >新增回复</el-button>
                    <el-button type="primary" size="small" @click="showDetialQuestion(scope.row)">编辑</el-button>
                    <el-button
                      type="danger"
                      size="small"
                      @click="handlerDelQuestion(scope.row.id)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="queType" label="问题类型" width="100">
          <template slot-scope="scoped">
            <div>
              <el-tag v-if="scoped.row.queType==1" type="primary">常见问题</el-tag>
              <el-tag v-else-if="scoped.row.queType==2" type="success">详细问题</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="queTitle" label="标题" width="300"></el-table-column>
        <el-table-column prop="queKeyword" label="	关键字" width="300">
          <template slot-scope="scoped">
            <div>
              <el-tag
                type="info"
                v-for="(item,index) in scoped.row.queKeyword"
                :key="index"
              >{{item}}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="queDescribe" label="描述" width="300"></el-table-column>
        <el-table-column prop="companyName" label="公司名"></el-table-column>
        <el-table-column prop="deviceTypeName" label="设备类型名称"></el-table-column>
        <!-- <el-table-column prop="isHaveAns" label="是否有回复">
          <template slot-scope="scoped">
            <div>
              <el-link v-if="scoped.row.isHaveAns==1" type="success">有回复</el-link>
              <el-link v-else-if="scoped.row.isHaveAns==2" type="danger">无回复</el-link>
            </div>
          </template>
        </el-table-column>-->
        <el-table-column fixed="right" label="操作" width="300">
          <template slot-scope="scope">
            <el-button
              type="success"
              size="small"
              @click="showAddDetailQuestion(scope.row.id)"
            >添加详细问题</el-button>
            <el-button type="primary" size="small" @click="showEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handlerDelQuestion(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination" style="margin-bottom:20px;">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[5,10, 15, 20,25]"
          :page-size="questionQuery.pageSize"
          :current-page="questionQuery.pageNumber"
          layout="total, sizes, prev, pager, next, jumper"
          :total="count"
          class="management_page"
        ></el-pagination>
      </div>
      <!-- 问题弹框 -->
      <el-dialog
        :title="questionName"
        :visible.sync="dialogVisibleQuestion"
        width="30%"
        :before-close="handleCloseQuestion"
      >
        <el-form
          :model="questionForm"
          :rules="questionRules"
          ref="quesionRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <!-- <el-form-item label="问题类型" prop="queType">
            <el-select
              v-model="questionForm.queType"
              placeholder="请选择问题类型"
              @change="showDetialQuestion"
              :disabled="questionTypeDisabled"
            >
              <el-option
                v-for="item in queTypeList"
                :label="item.name"
                :value="item.queType"
                :key="item.queType"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="常见问题" prop="queId" v-if="selectId==2">
            <el-select v-model="questionForm.queId" placeholder="请选择问题类型">
              <el-option
                v-for="item in priaryquestionList"
                :label="item.queTitle"
                :value="item.queId"
                :key="item.queId"
              ></el-option>
            </el-select>
          </el-form-item>-->
          <el-form-item label="	问题标题" prop="queTitle">
            <el-input v-model="questionForm.queTitle" placeholder="请输入问题标题"></el-input>
          </el-form-item>
          <el-form-item label="问题关键字" prop="queKeyword">
            <el-tag
              :key="tag"
              v-for="tag in dynamicTags"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)"
            >{{tag}}</el-tag>
            <el-input
              class="input-new-tag"
              v-if="inputVisible"
              v-model="inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
            ></el-input>
            <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新增关键字</el-button>
          </el-form-item>
          <el-form-item label="	描述" prop="queDescribe">
            <el-input type="textarea" v-model="questionForm.queDescribe" placeholder="请输入问题的描述"></el-input>
          </el-form-item>
          <el-form-item label="	排序" prop="sort">
            <el-input v-model="questionForm.sort" placeholder="请输入问题的顺序(越大越优先)"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleQuestion = false">取 消</el-button>
          <el-button type="primary" @click="handlerSure">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 回答弹框-->
      <el-drawer
        :title="anwerName"
        :visible.sync="drawer"
        :direction="direction"
        :before-close="handleClosequestion"
      >
        <el-form :model="answerForm" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="回复内容" prop="name">
            <Editor
              :content="answerForm.answerContent"
              @onEditorChange="getedirotContent($event)"
              ref="editor"
            />
          </el-form-item>
          <el-form-item label="视频讲解" prop="name">
            <UploadVideo @getVideo="handlerVideo" :list="answerForm.fileList" />
          </el-form-item>
        </el-form>
        <div class="el-drawer__footer">
          <el-button type="primary" @click="handlerSureDrawer">确定</el-button>
          <el-button @click="handlerQuxiao">取 消</el-button>
          <el-button type="danger" v-if="anwerName=='查看回复'" @click="handlerDel">删除回复</el-button>
        </div>
      </el-drawer>
    </el-card>
  </div>
</template>

<script>
import {
  getRobotQuesListType,
  insertQuestionType,
  updateQuestion,
  deleteQuestion,
  insertAnswer,
  getAnswerList,
  updateAnswer,
  deleteAnswer,
  comGetDetQueList,
  getCommonQueList
} from "../../utils/api";
import { mapState, mapGetters } from "vuex";
import Editor from "../../components/Editor";
import UploadVideo from "../../components/UploadVideo";
export default {
  inject: ["reload"],
  data() {
    return {
      value1: "",
      // 开关的值
      value: "",
      contentStr: " ",
      // 问题列表
      questionList: [],
      // 总条数
      count: 0,
      //   分页
      questionQuery: {
        pageNumber: 1,
        pageSize: 5,
        queTitle: "",
        queKeyword: "",
        deviceTypeId: ""
      },
      //   问题的显示隐藏
      dialogVisibleQuestion: false,
      //   判断是添加问题还是编辑问题
      questionName: "添加常见问题",
      //   问题表单
      questionForm: {
        queType: "",
        queTitle: "",
        queKeyword: "",
        queDescribe: "",
        sort: "",
        companyId: "",
        queId: "",
        deviceTypeId: ""
      },
      //   问题类型数据
      queTypeList: [
        {
          queType: 1,
          name: "常见问题"
        },
        {
          queType: 2,
          name: "详细问题"
        }
      ],
      //   问题的校验
      questionRules: {
        queType: [
          { required: true, message: "请选择问题类型", trigger: "blur" }
        ],
        queId: [{ required: true, message: "请选择常见问题", trigger: "blur" }],
        queTitle: [
          { required: true, message: "请填写问题标题", trigger: "blur" }
        ],
        queDescribe: [
          { required: true, message: "请填写描述", trigger: "blur" }
        ],
        sort: [{ required: true, message: "请填写顺序", trigger: "blur" }]
      },
      //   添加关键字的数据
      dynamicTags: [],
      //   输入框的显示隐藏
      inputVisible: false,
      //   输入框的值
      inputValue: "",
      //   判断是添加回答还是查看回答
      anwerName: "新增回复",
      //回答的弹框出现位置
      direction: "rtl",
      //   回答的弹框的显示隐藏
      drawer: false,
      arr1: {},
      arr2: {},
      answerForm: {
        answerContent: "",
        fileList: "",
        queId: "",
        companyId: "",
        answerJson: []
      },
      // 常见问题的id
      primaryId: "",
      // 常见问题的详情数据
      detialList: [],
      // 问题类型的id
      selectId: "",
      // 常见问题的数据
      priaryquestionList: [],
      questionTypeDisabled: false,
      getRowKeys(row) {
        return row.id;
      },
      expands: [],
      // 是否显示表头
      showHeader: false
    };
  },
  components: {
    Editor,
    UploadVideo
  },
  computed: {
    ...mapState(["org_id"])
  },
  watch: {
    org_id(val) {}
  },
  created() {
    this.getRobotQuestion();
  },
  methods: {
    // 展开行事件
    exChange(row, expandedRows) {
      var that = this;
      if (expandedRows.length) {
        that.expands = [];
        if (row) {
          that.expands.push(row.id);
        }
      } else {
        that.expands = [];
      }
      this.primaryId = row.id;
      this.showDetial();
    },
    // 根据展开行调详情接口
    showDetial() {
      this.showDetialDown();
    },
    // 下边展开行的数据
    showDetialDown() {
      const params = {
        queId: this.primaryId
      };
      this.postRequest(comGetDetQueList, params).then(res => {
        if (res.code == 200) {
          this.detialList = res.data;
          res.data.map(item => {
            item.queKeyword = item.queKeyword.split(",");
          });
        }
      });
    },
    // 选择问题的时候触发的函数
    showDetialQuestion(val) {
      this.selectId = val;
      this.postRequest(getCommonQueList, {
        deviceModelId: window.sessionStorage.getItem("ModelID")
      }).then(res => {
        if (res.code == 200) {
          this.priaryquestionList = res.data;
        }
      });
    },
    //   获取问题列表
    getRobotQuestion() {
      this.questionQuery.deviceTypeId = window.sessionStorage.getItem(
        "deviceTypeid"
      );
      this.postRequest(getRobotQuesListType, this.questionQuery).then(res => {
        if (res.code == 200) {
          this.questionList = res.data.list;
          this.count = res.data.count;
          res.data.list.map(item => {
            item.queKeyword = item.queKeyword.split(",");
          });
        }
      });
    },
    // 点击新增问题显示弹框
    showAddQuestion() {
      this.questionName = "添加常见问题";
      this.questionTypeDisabled = false;
      this.dialogVisibleQuestion = !this.dialogVisibleQuestion;
    },
    // 点击添加详细问题弹框
    showAddDetailQuestion(id) {
      this.questionName = "添加详细问题";
      this.questionTypeDisabled = false;
      this.dialogVisibleQuestion = !this.dialogVisibleQuestion;
      this.questionForm.queId = id;
    },
    // 点击常见问题编辑显示弹框
    showEdit(data) {
      this.$nextTick(() => {
        this.dynamicTags = data.queKeyword;
        this.questionTypeDisabled = true;
        this.questionName = "编辑常见问题";
        this.dialogVisibleQuestion = !this.dialogVisibleQuestion;
        this.questionForm.queId = data.id;
        this.questionForm.queType = data.queType;
        this.questionForm.queTitle = data.queTitle;
        this.questionForm.queKeyword = this.dynamicTags;
        this.questionForm.sort = data.sort;
        this.questionForm.queDescribe = data.queDescribe;
      });
    },
    // 点击编辑详细问题显示弹框
    showDetialQuestion(data) {
      this.$nextTick(() => {
        this.dynamicTags = data.queKeyword;
        this.questionTypeDisabled = true;
        this.questionName = "编辑详细问题";
        this.dialogVisibleQuestion = !this.dialogVisibleQuestion;
        this.questionForm.queId = data.id;
        this.questionForm.queType = data.queType;
        this.questionForm.queTitle = data.queTitle;
        this.questionForm.queKeyword = this.dynamicTags;
        this.questionForm.sort = data.sort;
        this.questionForm.queDescribe = data.queDescribe;
      });
    },
    // 封装一个添加详细问题的方法
    handlerDetialAdd() {
      this.questionForm.queType = 2;
      this.questionForm.deviceTypeId = window.sessionStorage.getItem(
        "deviceTypeid"
      );
      this.questionForm.companyId = this.org_id;
      this.questionForm.queKeyword = this.dynamicTags.join(",");
      this.postRequest(insertQuestionType, this.questionForm).then(res => {
        if (res.code == 200) {
          this.$message.success("添加详细问题成功");
          this.dialogVisibleQuestion = false;
          this.getRobotQuestion();
          this.reload();
        }
      });
    },
    // 封装一个添加常见问题的方法
    handlerAdd() {
      this.questionForm.deviceTypeId = window.sessionStorage.getItem(
        "deviceTypeid"
      );
      this.questionForm.queType = 1;
      this.questionForm.queId = 0;
      this.questionForm.companyId = this.org_id;
      this.questionForm.queKeyword = this.dynamicTags.join(",");
      this.postRequest(insertQuestionType, this.questionForm).then(res => {
        if (res.code == 200) {
          this.$message.success("添加常见问题成功");
          this.dialogVisibleQuestion = false;
          this.getRobotQuestion();
          this.$refs.quesionRef.resetFields();
          this.questionForm.queTitle = "";
          this.questionForm.queKeyword = "";
          this.questionForm.queDescribe = "";
          this.questionForm.sort = "";
        }
      });
    },
    // 封装一个编辑问题的方法
    handlerEdit() {
      this.questionForm.queKeyword = this.dynamicTags.join(",");
      this.postRequest(updateQuestion, this.questionForm).then(res => {
        if (res.code == 200) {
          this.$message.success("编辑问题成功");
          this.dialogVisibleQuestion = false;
          this.getRobotQuestion();
        }
      });
    },
    // 封装一个详细问题
    handlerDetialEdit() {
      this.questionForm.queType = 2;
      this.questionForm.queKeyword = this.dynamicTags.join(",");
      this.postRequest(updateQuestion, this.questionForm).then(res => {
        if (res.code == 200) {
          this.$message.success("编辑问题成功");
          this.dialogVisibleQuestion = false;
          this.reload();
        }
      });
    },
    // 点击确定判断是添加问题还是编辑问题
    handlerSure() {
      this.$refs.quesionRef.validate(valid => {
        if (!valid) return this.$message.error("请填写完整");
        if (this.questionName == "添加常见问题") {
          this.handlerAdd();
        } else if (this.questionName == "编辑常见问题") {
          this.handlerEdit();
        } else if (this.questionName == "添加详细问题") {
          this.handlerDetialAdd();
        } else if (this.questionName == "编辑详细问题") {
          this.handlerDetialEdit();
        }
      });
    },
    // 点击删除问题
    handlerDelQuestion(id) {
      const params = {
        queId: id
      };
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.postRequest(deleteQuestion, params).then(res => {
            if ((res.code = 200)) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.getRobotQuestion();
              this.showDetialDown();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //   点击返回 返回上一级
    goBack() {
      this.$store.dispatch("delVisitedViews", this.$route).then(obj => {
        this.$router.push("/DeviceType");
      });
      window.sessionStorage.removeItem("deviceTypeId");
    },
    // 查看回答的弹框
    shoAnswer(id) {},
    // 新增回答的弹框
    addAnswer(id) {
      this.anwerName = "新增回复";
      this.answerForm.queId = id;
      this.drawer = !this.drawer;
    },
    // 获取富文本
    getedirotContent(val) {
      this.arr1.ansType = 1;
      this.answerForm.answerContent = val;
      this.arr1.fileUrl = "";
      this.arr1.fileName = "";
      this.arr1.fileType = "";
      this.answerForm.answerJson[0] = this.arr1;
    },
    // 获取视频
    handlerVideo(val) {
      this.arr2.ansType = 2;
      this.arr2.ansContent = "";
      this.arr2.fileUrl = val[0].fileUrl;
      this.arr2.fileName = val[0].fileName;
      this.arr2.fileType = val[0].fileType;
      this.answerForm.answerJson[1] = this.arr2;
    },
    // 封装一个添加回复的方法
    handlerAddAnser() {
      this.answerForm.companyId = this.org_id;
      this.arr1.ansContent = this.answerForm.answerContent;
      this.answerForm.answerJson = JSON.stringify(this.answerForm.answerJson);
      this.postRequest(insertAnswer, this.answerForm).then(res => {
        if (res.code == 200) {
          this.$message.success("新增回复成功");
          this.getRobotQuestion();
          this.drawer = false;
          this.reload();
        }
      });
    },
    // 封装一个查看回复的方法
    showAnswer(id) {
      this.answerForm.queId = id;
      this.anwerName = "查看回复";
      this.drawer = !this.drawer;
      this.postRequest(getAnswerList, { queId: id }).then(res => {
        if (res.code == 200) {
          this.answerForm.answerContent = res.data[0].ansContent;
          if (res.data[1]) {
            this.answerForm.fileList = res.data[1].fileUrl.split(",");
          } else {
          }
        }
      });
    },
    // 封装一个更新的方法
    handlerEditAnser() {
      this.arr1.ansContent = this.answerForm.answerContent;
      // console.log( this.arr2.fileUrl)
      // this.arr2.fileUrl= this.answerForm.fileList
      this.answerForm.companyId = this.org_id;
      this.answerForm.answerJson = JSON.stringify(this.answerForm.answerJson);
      this.postRequest(updateAnswer, this.answerForm).then(res => {
        if (res.code == 200) {
          this.$message.success("编辑回复成功");
          this.getRobotQuestion();
          this.drawer = false;
          this.reload();
        }
      });
    },
    // 点击确定判断是添加回复还是编辑回复
    handlerSureDrawer() {
      if (this.anwerName == "新增回复") {
        this.handlerAddAnser();
      } else if (this.anwerName == "查看回复") {
        this.handlerEditAnser();
      }
    },
    // 删除回复
    handlerDel() {
      const params = {
        queId: this.answerForm.queId
      };
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.postRequest(deleteAnswer, params).then(res => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.drawer = false;
              this.reload();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //分页
    handleSizeChange(val) {
      //每页条数
      this.questionQuery.pageSize = val;
      this.getRobotQuestion();
    },
    handleCurrentChange(val) {
      //当前第几页
      this.questionQuery.pageNumber = val;
      this.getRobotQuestion();
    },

    //点击空白
    handleCloseQuestion() {
      this.dialogVisibleQuestion = false;
      this.$refs.quesionRef.resetFields();
      this.questionForm.queTitle = "";
      this.questionForm.queKeyword = "";
      this.questionForm.queDescribe = "";
      this.questionForm.sort = "";

      this.dynamicTags = [];
    },
    // 点击问题空白处触发的事件
    handleClosequestion() {
      this.drawer = false;

      this.arr2.fileUrl = "";

      this.$refs.editor.clear();
      this.reload();
    },
    handlerQuxiao() {
      this.drawer = false;
      this.reload();
    },
    // 点击关闭标签
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },
    //显示输入框
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    }
  }
};
</script>

<style lang="less" scoped>
.demo-form-inline {
  border: 1px solid #ebeef5;
  margin-bottom: 20px;
  padding-left: 10px;
  .el-form-item {
    padding-top: 20px;
  }
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>